package com.chookss.home.knowledge.adaper;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.document.DocumentPreviewActivity;
import com.chookss.home.document.DownloadService;
import com.chookss.home.entity.DocunmentEntity;
import com.chookss.home.entity.LogEntity;
import com.chookss.tools.MyToast;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.annotations.Nullable;

public class LogDocunmentAdapter extends BaseQuickAdapter<LogEntity.DocunmentBean, BaseViewHolderEx> {
    private Activity context;
    private String tag;//记录来源
    private int status;//发布模式，可以修改 但是不能查看大图不能播放视频  1 发布成功正常详情页可以2发布中的详情页不得操作

    public LogDocunmentAdapter(int layoutResId, Activity context, @Nullable List<LogEntity.DocunmentBean> data,int status, String tag) {
        super(layoutResId, data);
        this.context = context;
        this.tag = tag;
        this.status = status;
    }

    @Override
    protected void convert(BaseViewHolderEx helper, LogEntity.DocunmentBean entity) {
        ImageView ivIconType = helper.getView(R.id.ivIconType);
        LinearLayout llMore = helper.getView(R.id.llMore);
        LinearLayout llInit = helper.getView(R.id.llInit);
        LinearLayout llContent = helper.getView(R.id.llContent);
        TextView tvItemTitle = helper.getView(R.id.tvItemTitle);
        TextView tvTime = helper.getView(R.id.tvTime);
        TextView tvSize = helper.getView(R.id.tvSize);
        TextView tvUpload = helper.getView(R.id.tvUpload);
        ProgressBar progressBar = helper.getView(R.id.progressBar);
        tvItemTitle.setText(entity.getDataTitle());
        if (entity.getProgress() == 0 || entity.getProgress() == 100) {
            progressBar.setVisibility(View.GONE);
        } else {
            progressBar.setVisibility(View.VISIBLE);
            progressBar.setProgress(entity.getProgress());
        }
        LinearLayout.LayoutParams params= (LinearLayout.LayoutParams) llContent.getLayoutParams();
        params.setMargins(Utils.dip2px(context,8),0,Utils.dip2px(context,15),0);
        llContent.setLayoutParams(params);
        llMore.setVisibility(View.GONE);
        String fileType = entity.getDataType();//文件类型1--word 2 --excel 3--PPT  4pdf
        if ("1".equals(fileType)) {
            Glide.with(context).load(R.drawable.icon_w_80).into(ivIconType);
        } else if ("2".equals(fileType)) {
            Glide.with(context).load(R.drawable.icon_x_80).into(ivIconType);
        } else if ("3".equals(fileType)) {
            Glide.with(context).load(R.drawable.icon_p_80).into(ivIconType);
        } else if ("4".equals(fileType)) {
            Glide.with(context).load(R.drawable.icon_pdf_80).into(ivIconType);
        } else {
            Glide.with(context).load(R.drawable.icon_mr_80).into(ivIconType);
        }
        tvTime.setText(Utils.getAccurateDate(entity.getDataTime()));
        tvSize.setText(Utils.changeKM(entity.getDataSize()));
        if(status==0){
            tvUpload.setVisibility(View.VISIBLE);
        }else{
            tvUpload.setVisibility(View.GONE);
        }
        helper.getItemView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Urls.antiShake.check()) {
                    return;
                }
                if(status==0){
                    MyToast.show("文件上传中");
                }else if(status==1){
                    requestSTORAGE(entity.getDataCode(), tvItemTitle.getText().toString(), helper.getItemPosition());
                }
            }
        });
    }

    private void requestSTORAGE(String code, String retitle, int rePosition) {
        XXPermissions.with(context)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            getDocunmentDetail(code, retitle, rePosition);
                        } else {
                            MyToast.show("存储未被授权，请先去权限设置里面授权");
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(context, denied, quick);
                    }
                });
    }

    private void getDocunmentDetail(String code, String docTitle, int docPosition) {
        Map<String, String> map = new HashMap<>();
        map.put("dataCode", code);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<DocunmentEntity>>() {
        }.getType(), null, Urls.getDetail, SignUtils2.makeSignStr(map), false, new ObserverCallback<DocunmentEntity>() {
            @Override
            public void onSuccess(DocunmentEntity newData) {
                if (newData != null) {
                    openFile(newData, docTitle, docPosition);
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void openFile(DocunmentEntity entity, String title, int position) {
        if (!Utils.isNull(entity.getDataUrl())) {
            String url, name, fileUrl, urls;
            url = entity.getDataUrl();
            urls = url.split("\\?")[0];
            fileUrl = urls.substring(urls.lastIndexOf("/") + 1, urls.length());
            if (MyApp.downloadFiles.contains(title)||!MyApp.mIsInitTBSSuccess) {
                if (!MyApp.docunmentOpen) {
                    Intent intent = new Intent(context, DocumentPreviewActivity.class);
                    intent.putExtra("fileUrl", fileUrl);
                    intent.putExtra("fileName", title);
                    intent.putExtra("dataCode", entity.getDataCode());
                    context.startActivity(intent);
                }
            } else {
//                    downTask(url, title, entity, position);
                entity.setProgress(1);
                notifyItemChanged(position);
                Intent intent = new Intent(context, DownloadService.class);
                intent.putExtra("fileUrl", fileUrl);
                intent.putExtra("fileName", title);
                intent.putExtra("url", url);
                intent.putExtra("dataCode", entity.getDataCode());
                intent.putExtra("position", position);
                intent.putExtra("tag", tag);
                context.startService(intent);
            }

        }
    }

}
